import Axios from 'axios'
import { getCache } from './cache'
import { RESPONSE_STATUS } from '@/enums/httpEnum'
import { CACHE_KEY } from '@/enums/cacheEnum'

const request = Axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 10000
})

// 创建一个请求拦截器
request.interceptors.request.use((config) => {
  const token = getCache(CACHE_KEY.TOKEN)
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// 创建一个响应拦截器
request.interceptors.response.use(
  (response) => {
    if (response.status !== 200) {
      window.$message.error(response.statusText)
      return Promise.reject(new Error(response.statusText))
    }

    let errorMsg = ''

    const { code, msg, data } = response.data

    if (code === RESPONSE_STATUS.SUCCESS) {
      return data
    }

    switch (code) {
      case RESPONSE_STATUS.TIMEOUT:
        errorMsg = '登录过期，请重新登录'
        break
      default:
        errorMsg = msg
    }

    window.$message.error(errorMsg)

    throw new Error(errorMsg || '请求错误')
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default request
